package com.zxinlee.storage.tcc.impl;

import com.zxinlee.storage.entity.Storage;
import com.zxinlee.storage.mapper.StorageMapper;
import com.zxinlee.storage.tcc.ResultHolder;
import com.zxinlee.storage.tcc.StorageTccAction;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class StorageTccActionImpl implements StorageTccAction {

    @Autowired
    private StorageMapper storageMapper;

    @Transactional
    @Override
    public boolean prepare(BusinessActionContext businessActionContext, Long productId, Integer count) {
        //先查询库存是否够用
        Storage storage = storageMapper.findByProductId(productId);
        if (storage.getResidue() < count) {
            throw new RuntimeException("可用库存不足");
        }
        //冻结需要的商品
        storageMapper.updateResidueToFrozen(productId, count);

        //一阶段成功,添加成功标记  两层Map指向标记 {StorageTccAction.class : {事务ID : "p"}}
        ResultHolder.setResult(StorageTccAction.class, businessActionContext.getXid(), "p");

        return true;
    }

    @Transactional
    @Override
    public boolean commit(BusinessActionContext businessActionContext) {

        //二阶段执行之前,判断
        //如果没有标记(1.一阶段没成功 2.二阶段已经执行过了(rollback)),则不执行二阶段操作(commit),防止重复执行二阶段
        if (ResultHolder.getResult(StorageTccAction.class, businessActionContext.getXid()) == null)
            return true;

        Long productId = Long.valueOf(businessActionContext.getActionContext("productId").toString());
        Integer count = Integer.valueOf(businessActionContext.getActionContext("count").toString());
        storageMapper.updateFrozenToUsed(productId, count);

        //第二阶段完成时,删除标记 依据Map的两层key值找到标记
        ResultHolder.removeResult(StorageTccAction.class, businessActionContext.getXid());

        return true;
    }

    @Transactional
    @Override
    public boolean rollback(BusinessActionContext businessActionContext) {

        //二阶段执行之前,判断
        //如果没有标记(1.一阶段没成功 2.二阶段已经执行过了(commit)),则不执行二阶段操作(rollback),防止重复执行二阶段
        if (ResultHolder.getResult(StorageTccAction.class, businessActionContext.getXid()) == null)
            return true;

        Long productId = Long.valueOf(businessActionContext.getActionContext("productId").toString());
        Integer count = Integer.valueOf(businessActionContext.getActionContext("count").toString());
        storageMapper.updateFrozenToResidue(productId, count);

        //第二阶段完成时,删除标记 依据Map的两层key值找到标记
        ResultHolder.removeResult(StorageTccAction.class, businessActionContext.getXid());

        return true;
    }
}
